<template>
  <!-- 统计汇总 -->
  <a-collapse
    v-model="activeKey"
    :bordered="false"
    expand-icon-position="right" 
    class="mb12"
  >
    <a-collapse-panel
      style="background: #e6f3fc; border: none"
      :show-arrow="false"
    >
      <template slot="header">
        <a-row
          type="flex"
          justify="space-between"
          align="middle"
          style="width: 100%"
        >
          <div>
            {{ title || $route.meta.title }}
            <!-- 遍历汇总集合 -->
            <span
              v-for="(item, index) in countList"
              :key="index"
            >{{ item.title }}
              <a v-if="item.value=='selectLength'"><b>{{ selectLength || 0 }}</b></a>
              <a v-else><b>{{ countInfo[item.value] || 0 }}</b></a>{{ !item.needUnit ? '' : item.unit || '个'
              }}{{ index != countList.length - 1 ? '，' : '' }}</span>
          </div>
          <div>
            <a class="btn_right">
              <span>{{ activeKey.length > 0 ? '收起' : '展开' }}详细汇总信息</span>
              <a-icon :type="activeKey.length > 0 ? 'up' : 'down'" />
            </a>
          </div>
        </a-row>
      </template>
      <div>
        <div class="about-master-container">
          <a-form-model
            ref="form"
            :model="queryParam"
          >
            <a-row>
              <a-col span="8">
                <a-form-model-item
                  label="排名逻辑"
                  class="requiredFormItem"
                >
                  <a-select
                    v-model="sortType"
                    placeholder="请选择"
                    @change="refresh"
                  >
                    <a-select-option
                      v-for="(item,index) in typeList"
                      :key="index"
                      :value="item.key"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item
                  label="时间选择"
                  class="requiredFormItem"
                >
                  <a-range-picker
                    v-model="queryParam.searchTime"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-button
                  type="primary"
                  style="margin-left: 20px;"
                  @click="search"
                >
                  确定
                </a-button>
                <a-button
                  type="primary"
                  style="margin-left: 20px;"
                  :loading="expLoading"
                  @click="dataCountListExportExcelFn" 
                  v-btn-permission="'stm_005_exp_11'"
                >
                  导出
                </a-button>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
        <a-tabs
          :active-key="countTableType"
          @change="switchSummary"
        >
          <a-tab-pane
            :key="1"
            tab="分公司排名"
          />
          <a-tab-pane
            :key="2"
            tab="项目排名"
          />
          <a-tab-pane
            :key="3"
            tab="内部完成人排名"
          />
          <a-tab-pane
            :key="4"
            tab="外部完成人排名"
          />
        </a-tabs>
        <a-card>
          <b-table
          :loading="tableLoading"
            class="summary-table"
            ref="tableSummary"
            :show-page="false"
            :columns="columnsTotal"
            :request="loadDataSummary"
          />
        </a-card>
      </div>
    </a-collapse-panel>
  </a-collapse>
</template>

<script>
import { Collapse } from 'ant-design-vue'
import { getPlansCollect } from '@/api/science'
import { dataCountList,dataCountListExportExcel } from '@/api/achievementsManage'

export default {
  name: 'AuditSummary',
  components: {
    ACollapse: Collapse,
    ACollapsePanel: Collapse['Panel']
  },
  props: {
    // 标题
    title: {
      type: String,
      default: () => ''
    },
    selectLength:{
      type: Number,
      default: () => 0
    },
    countList: {
      type: Array,
      default: () => [
        {
          title: '总数：',
          value: 'total'
        },
        {
          title: '待提交审核：',
          value: 'draftNum'
        },
        {
          title: '审核中：',
          value: 'submittedNum'
        },
        {
          title: '审核通过：',
          value: 'pastNum'
        },
        {
          title: '审核不通过：',
          value: 'rejectedNum'
        }
      ]
    },
    // api
    api: {
      type: Object,
      default: () => ({})
    },
    // 请求参数
    form: {
      type: Object,
      default: () => ({})
    },
    // 加载表格计数器
    loadCount: {
      type: [Number, String],
      default: () => 0
    }
  },
  watch: {
    // 加载表格计数器
    loadCount() {
      this.$nextTick(this.getCount)
    }
  },
  computed: {
    // eslint-disable-next-line vue/return-in-computed-property
    columnsTotal() {
      let header = [
        {
          title: '分公司名称',
          dataIndex: 'typeName'
        },
        {
          title: '项目名称',
          dataIndex: 'typeName'
        },
        {
          title: '完成人名称',
          dataIndex: 'typeName'
        }
      ]
      if (this.countTableType === 1) return [{
        title: '排名',
        width: 80,
        customRender() {
          return arguments[2] + 1
        }
      }, header[0], ...this.columnsTotalTemp]
      // if (this.countTableType === 2) return [header[0], header[1], ...this.columnsTotalTemp]
      if (this.countTableType === 2) return [{
        title: '排名',
        width: 80,
        customRender() {
          return arguments[2] + 1
        }
      }, header[1], ...this.columnsTotalTemp]
      if (this.countTableType === 3) return [{
        title: '排名',
        width: 80,
        customRender() {
          return arguments[2] + 1
        }
      }, header[2], ...this.columnsTotalTemp]
      if (this.countTableType === 4) return [{
        title: '排名',
        width: 80,
        customRender() {
          return arguments[2] + 1
        }
      }, header[2], ...this.columnsTotalTemp]
    }
  },
  data() {
    return {
      sortType: undefined,
      countInfo: {}, // 汇总对象
      activeKey: [],
      expLoading: false,
      tableLoading: false,
      queryParam: {
        type: undefined
      },
      typeList: [
        { name: '根据总数量', key: 'totalNum' },
        { name: '根据科技奖数量', key: 'teachNum' },
        { name: '根据研发立项数量', key: 'researchNum' },
        { name: '根据工法数量', key: 'constructionNum' },
        { name: '根据国家知识产权数量', key: 'intellectualPropertyNum' },
        { name: '根据论文数量', key: 'paperNum' },
        { name: '根据科技成果评价数量', key: 'achievementAppraiseNum' },
        { name: '根据科技查新数量', key: 'findNewNum' }
      ],
      countTableType: 1,
      args: {},
      columnsTotalTemp: [
        { title: '获得总数量', dataIndex: 'totalNum' },
        { title: '科技奖获得数量', dataIndex: 'teachNum' },
        { title: '研发立项获得数量', dataIndex: 'researchNum' },
        { title: '工法获得数量', dataIndex: 'constructionNum' },
        { title: '国家知识产权获得数量', dataIndex: 'intellectualPropertyNum' },
        { title: '论文获得数量', dataIndex: 'paperNum' },
        { title: '科技成果评价获得数量', dataIndex: 'achievementAppraiseNum' },
        { title: '科技查新获得数量', dataIndex: 'findNewNum' }
      ],
      loadDataSummary: async () => {
        this.tableLoading = true
        setTimeout(() => {
          this.tableLoading = false
        }, 3000);
        let params = { type: this.countTableType }
        if (this.queryParam.searchTime) {
          params.startTime = this.queryParam.searchTime[0]
          params.endTime = this.queryParam.searchTime[1]
        }
        let res = await dataCountList(Object.assign(params, this.form))
        if (res.code === this.SUCCESS_CODE) {
          if (this.sortType) {
            res.data.sort((v1, v2) => v2[this.sortType] - v1[this.sortType])
          }
          this.tableLoading = false
          return { code: this.SUCCESS_CODE, data: res.data }
          
        } else {
          this.tableLoading = false
          return { code: this.SUCCESS_CODE, data: [] }
        }
      }
    }
  },
  created() {
    // 获取统计信息
    this.getCount()
  },
  methods: {
    /**
     * 导出科技管理计划统计 
     * @param parameter
     */
      async dataCountListExportExcelFn(){
        this.expLoading = true
        let params = { type: this.countTableType,searchTime:this.queryParam.searchTime }
        // let expqueryParam = Object.assign({}, params,this.$parent.$parent.$parent.$parent.$refs.searchData.form.getFieldsValue());
        if (params.searchTime) {
          params.startTime = params.searchTime[0]
          params.endTime = params.searchTime[1]
        }
        delete params.searchTime
        let res = await dataCountListExportExcel(params)
        if (res.data){
          this.expLoading = false
        }else {
          this.expLoading = false
        }
        this.handleDownload(res)
    },
    /**
     * 转义下载
     * @param parameter
     */
     handleDownload(res){
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename.substring(filename.indexOf("''") + 2) // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
    refresh() {
      let index = this.typeList.findIndex(v => v.key === this.sortType)
      if (index!==-1){
        let ths = document.querySelectorAll('.summary-table th')
        ths.forEach(v=>{
          v.classList.remove('blue')
        })
        ths[2 + index].classList.add('blue')
      }
      this.$refs.tableSummary?.getData(null, true)
    },
    search() {
      this.$refs.tableSummary?.getData(null, true)
    },
    // 切换汇总信息
    switchSummary(e) {
      this.countTableType = e
      this.$refs.tableSummary.getData(null, true)
    },
    /**
     * 获取统计
     */
    getCount() {
      this.api?.count(this.form).then((res) => {
        this.countInfo = res.data
      })
    }
  }
}
</script>
<style>
.blue {
  background: rgb(2, 167, 240) !important;
  color: white!important;
}
</style>
